package net.zretc.controller;

import net.zretc.entity.User;
import net.zretc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping
    public List<User> findAll() {
        try {
            return userService.findAll();
        } catch (Exception e) {
            System.err.println("获取用户列表出错: " + e.getMessage());
            return null;
        }
    }

    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody User user) {
        Map<String, Object> result = new HashMap<>();
        try {
            User loggedInUser = userService.login(user.getUsername(), user.getPassword());
            if (loggedInUser != null) {
                result.put("success", true);
                result.put("message", "登录成功");
                result.put("user", loggedInUser);
                if (loggedInUser.isAdmin()) {
                    result.put("userType", "admin");
                } else {
                    result.put("userType", "user");
                }
            } else {
                result.put("success", false);
                result.put("message", "用户名或密码错误");
            }
        } catch (Exception e) {
            System.err.println("登录出错: " + e.getMessage());
            result.put("success", false);
            result.put("message", "登录出错，请稍后再试");
        }
        return result;
    }

    @PostMapping("/register")
    public Map<String, Object> register(@RequestBody User user) {
        Map<String, Object> result = new HashMap<>();
        boolean success = userService.register(user);
        if (success) {
            result.put("success", true);
            result.put("message", "注册成功");
        } else {
            result.put("success", false);
            result.put("message", "注册失败，用户名可能已存在");
        }
        return result;
    }

    @PostMapping
    public int insert(@RequestBody User user) {
        try {
            return userService.insert(user);
        } catch (Exception e) {
            System.err.println("插入用户出错: " + e.getMessage());
            return 0;
        }
    }

    @PutMapping
    public int update(@RequestBody User user) {
        try {
            return userService.update(user);
        } catch (Exception e) {
            System.err.println("更新用户出错: " + e.getMessage());
            return 0;
        }
    }

    @DeleteMapping("/{userId}")
    public int delete(@PathVariable Integer userId) {
        try {
            return userService.delete(userId);
        } catch (Exception e) {
            System.err.println("删除用户出错: " + e.getMessage());
            return 0;
        }
    }
}
